﻿using System;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace CardPlay.Presentation.Drawing
{
    public static class Extensions
    {
        public static BitmapSource ToBitmapSource(this Bitmap sourceBitmap)
        {
            using (var handle = new BitmapHandle(sourceBitmap.GetHbitmap()))
            {
                return Imaging.CreateBitmapSourceFromHBitmap(
                    handle.DangerousGetHandle(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
            }
        }

        public static void SaveAsPng(this BitmapSource bitmap, string path)
        {
            using (var file = new FileStream(path, FileMode.Create))
            {
                var encoder = new PngBitmapEncoder
                {
                    Interlace = PngInterlaceOption.On
                };

                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                encoder.Save(file);
            }
        }
    }
}